<template>
  <div>
    <!-- 循环渲染帖子卡片 -->
    <a-list
        class="list-demo-action-layout"
        :bordered="false"
    >
      <a-list-item action-layout="vertical" v-if="props.data.length > 0">
        <a-card class="post" v-for="item in props.data" :key="item.id" @click="clickCard(item.id)" hoverable>
          <template #actions>
              <span class="action-item" @click.stop="clickThumbIcon(item)">
                <IconThumbUp :class="item.hasThumb ? 'icon-filled' : 'icon'" :size="iconSize"/>
                <a-typography-text class="icon-text">{{ item.thumbNum }}</a-typography-text>
              </span>
            <span class="action-item" @click.stop="clickFavourIcon(item)">
                <IconStar :class="item.hasFavour ? 'icon-filled' : 'icon'" :size="iconSize"/>
                <a-typography-text class="icon-text">{{ item.favourNum }}</a-typography-text>
              </span>
            <span class="action-item">
                <IconShareInternal class="icon" :size="iconSize" @click.stop="clickShareIcon"/>
              </span>
          </template>
          <template v-if="props.editable" #extra>
            <IconEdit class="icon" style="margin-right: 40px" :size="iconSize"
                      @click.stop="editPost(item.id)"/>
            <IconDelete class="icon" :size="iconSize"
                        @click.stop="() => { confirmVisible = true; deletePostId = item.id }"/>
          </template>
          <template #title>
            {{ item.title }}
          </template>
          <a-card-meta>
            <template #description>
              <a-typography-text :ellipsis="{rows: 5}">
                {{ item.content }}
              </a-typography-text>
            </template>
            <template #avatar>
              <UserAvatar
                  :user-id="item.userId"
                  :avatar-size="32"
                  :font-size="10"
              />
            </template>
          </a-card-meta>
        </a-card>
      </a-list-item>
      <!-- 每一页列表最后添加发布帖子按钮 -->
      <a-list-item v-if="props.publishable">
        <div style="display: flex; justify-content: center;">
          <a-button
              shape="circle"
              @click="showAddPostModal"
          >
            <IconPlus/>
          </a-button>
        </div>
      </a-list-item>
      <a-list-item>
        <div style="display: flex; justify-content: center;">
          <a-pagination
              :total="pageInfo.total"
              :current="pageInfo.current"
              :page-size="pageInfo.pageSize"
              show-jumper
              show-page-size
              @change="currentChange"
              @page-size-change="pageSizeChange"
          />
        </div>
      </a-list-item>
    </a-list>
    <!-- 浮窗展示帖子的详细信息 -->
    <a-modal v-model:visible="infoVisible" title-align="start" :width="1200"> <!-- 固定宽度为 600px -->
      <template #title v-if="post.userId>0">
        <UserAvatar
            :user-id="post.userId"
            :avatar-size="32"
            :font-size="10"
            @click="router.push('/otherProfile/'+post.userId)"
        />
      </template>
      <a-list scrollbar="scrollbar" :bordered="false" :split="false">
        <!-- 帖子信息区域 -->
        <a-list-item>
          <h1 style="text-align: center;">
            {{ post.title }}
          </h1>
          <v-md-preview :text="post.content"></v-md-preview>
        </a-list-item>
        <!-- 按钮区域 -->
        <a-list-item>
          <div style="display: flex; align-items: center; justify-content: start">
              <span class="action-item" @click.stop="clickThumbIcon(post)">
                <IconThumbUp :class="post.hasThumb ? 'icon-filled' : 'icon'" :size="iconSize"/>
                <a-typography-text class="icon-text">{{ post.thumbNum }}</a-typography-text>
              </span>
            <span class="action-item" @click.stop="clickFavourIcon(post)">
                <IconStar :class="post.hasFavour ? 'icon-filled' : 'icon'" :size="iconSize"/>
                <a-typography-text class="icon-text">{{ post.favourNum }}</a-typography-text>
              </span>
            <span class="action-item">
                <IconShareInternal class="icon" :size="iconSize" @click.stop="clickShareIcon"/>
              </span>
          </div>
        </a-list-item>
        <!-- 评论区域 -->
        <a-list-item>
          <CommentList
              :data="commentData"
              :author-id="post.userId"
              :post-id="post.id"
              @get-data="clickCard(post.id)"
          >
          </CommentList>
        </a-list-item>
      </a-list>
    </a-modal>
    <a-modal
        v-model:visible="confirmVisible"
        @ok="doDeletePost"
        :closable="false"
    >
      <div style="text-align: center">
        确认删除？
      </div>
    </a-modal>
    <!-- 发布和修改帖子弹窗 -->
    <a-modal v-model:visible="addOrEditVisible" title-align="start" @ok="submitAddOrEditPost" :width="1200">
      <template #title>
        <UserAvatar
            :user-id="loginUserStore.loginUser.id"
            :avatar-size="32"
            :font-size="10"
        />
      </template>
      <a-list :bordered="false" :split="false">
        <!-- 输入帖子内容 -->
        <a-list-item>
          <div style="text-align: center;margin-bottom: 20px">
            <a-input style="width: 60%;" placeholder="请输入帖子标题" v-model="addOrEditPost.title"></a-input>
          </div>
          <v-md-editor v-model="addOrEditPost.content" height="700px"></v-md-editor>
        </a-list-item>
      </a-list>
    </a-modal>
  </div>
</template>

<script setup>
import {
  IconThumbUp,
  IconShareInternal,
  IconStar,
  IconDelete,
  IconPlus,
  IconEdit,
} from '@arco-design/web-vue/es/icon';
import {onMounted, ref, defineProps, defineEmits} from "vue";
import {
  deletePostUsingPost,
  favourPost,
  getPostCommentByPostIdUsingGet,
  getPostVOByIdUsingGet,
  thumbPost,
  addPostUsingPost, editPostUsingPost, // 假设存在该接口用于发布帖子
} from "@/api/PostRequest";
import message from "@arco-design/web-vue/es/message";
import {useLoginUserStore} from "@/store/userStore";
import UserAvatar from "@/components/UserAvatar.vue";
import router from "@/router/router";
import { watch } from 'vue';
import CommentList from "@/components/CommentList.vue";

const props = defineProps(['data', 'publishable', 'editable' , 'total']);
const emit = defineEmits(['getData']);

const commentData = ref([]);
// 定义删除和添加的弹窗展示
const addOrEditVisible = ref(false);
const addOrEditPost = ref({});
let operateType = ref("add");
// 图标大小
const iconSize = ref(24);
// 定义悬浮窗是否展示
const infoVisible = ref(false);
// 定义展示 post 用的变量
const post = ref({
  title: '标题',
  content: '内容',
  userId: 0,
  user: {
    id: 0,
    userName: '用户名'
  }
});

const pageInfo = ref({
  current: 1,
  pageSize: 5,
  total: 0
})

// 定义提示框是否展示
const confirmVisible = ref(false);
// 定义即将删除的帖子 ID
const deletePostId = ref(0);

// 获取登录用户信息
const loginUserStore = useLoginUserStore();

// 监听 props.data 的变化
watch(() => props.total, (newData) => {
  pageInfo.value.total = newData
});

onMounted(async () => {
  await emit('getData', pageInfo.value.current, pageInfo.value.pageSize);
});

// 点击点赞图标
async function clickThumbIcon(item) {
  item.hasThumb = !item.hasThumb;
  // 从后端获取点赞数
  const result = await thumbPost(item.id);
  if (result.data.code === 0) {
    item.thumbNum += result.data.data;
  }
}

// 点击收藏图标
async function clickFavourIcon(item) {
  item.hasFavour = !item.hasFavour;
  // 从后端获取收藏数
  const result = await favourPost(item.id);
  if (result.data.code === 0) {
    item.favourNum += result.data.data;
  } else {
    message.error('当前帖子已被删除');
  }
}

// 点击分享按钮
async function clickShareIcon() {
  message.info("敬请期待~");
}

// 点击帖子卡片
async function clickCard(postId) {
  let result = await getPostVOByIdUsingGet(postId);
  if (result.data.code === 0) {
    post.value = result.data.data;
    console.log(post.value.userId);
  } else {
    message.error('获取帖子详细信息失败');
    infoVisible.value = false;
  }
  result = await getPostCommentByPostIdUsingGet(postId);
  if (result.data.code === 0) {
    commentData.value = result.data.data;
  }
  infoVisible.value = true;
}

// 执行删除操作
async function doDeletePost() {
  await deletePostUsingPost({
    id: deletePostId.value
  });
  await emit('getData' , pageInfo.value.current, pageInfo.value.pageSize);
  message.success("删除成功!");
}

// 显示发布帖子的按钮、弹窗以及相应的逻辑
function showAddPostModal() {
  addOrEditPost.value = {};
  addOrEditVisible.value = true;
  operateType.value = "add";
}

// 提交发布帖子信息
async function submitAddOrEditPost() {
  let result;
  if(operateType.value === 'add'){
    try {
      result = await addPostUsingPost(addOrEditPost.value);
    } catch (error) {
      message.error('帖子发布失败，请稍后重试');
    }
  }else if(operateType.value === 'edit'){
    try {
      result = await editPostUsingPost(addOrEditPost.value);
    }catch (error){
      message.error('帖子发布失败，请稍后重试');
    }
  }
  if (result.data.code === 0) {
    message.success('帖子修改成功');
  } else {
    message.error('帖子发布失败: ' + result.data.message);
  }
  addOrEditVisible.value = false;
  await emit('getData' , pageInfo.value.current, pageInfo.value.pageSize);
}

// 点击修改按钮后弹出修改框
async function editPost(postId) {
  operateType.value = "edit";
  addOrEditPost.value = {};
  addOrEditVisible.value = true;
  const result = await getPostVOByIdUsingGet(postId);
  addOrEditPost.value = result.data.data;
}

// 当前页码改变时触发emit调用
async function currentChange(current) {
  pageInfo.value.current = current;
  await emit('getData', pageInfo.value.current, pageInfo.value.pageSize);
}

// 当前页大小改变时触发emit调用
async function pageSizeChange(pageSize) {
  pageInfo.value.pageSize = pageSize;
  await emit('getData', pageInfo.value.current, pageInfo.value.pageSize);
}
</script>

<style scoped>
.action-item {
  display: flex;
  align-items: center; /* 垂直居中 */
  gap: 8px; /* 图标和文字间距 */
  margin-right: 40px;
  cursor: pointer;
}

/* 图标的文字样式 */
.icon-text {
  font-size: 14px; /* 文字大小 */
  line-height: 1; /* 避免文字高度影响布局 */
}

.icon, .icon-filled {
  border-radius: 50%;
  transition: all 0.1s;
}

.icon-filled {
  color: #1890ff !important;
  fill: currentColor !important;
}

/* 图标样式 */
.icon:hover {
  background-color: rgb(var(--gray-2));
}

.post {
  width: 100%;
  margin-bottom: 15px;
  margin-top: 15px;
}
</style>